/*
 * GenerateTocDialog.java
 *
 *  created: 2.11.2011
 *  charset: UTF-8
 *  license: MIT (X11) (See LICENSE file for full license)
 */
package cz.mp.k3bg.gui;

import cz.mp.k3bg.log.LoggerManager;
import cz.mp.k3bg.core.BookFiles;
import cz.mp.util.GuiUtils;
import cz.mp.k3bg.Images;
import cz.mp.k3bg.core.TocGenerator;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
import static cz.mp.k3bg.Images.*;
import static cz.mp.k3bg.TextSource.*;

/**
 * Dialog pro generování obsahu knihy ze zadaných souborů těla knihy.
 *
 * @author Martin Pokorný
 * @version 0.1
 * @see TocGenerator  
 */
public class GenerateTocDialog extends GenerateDialog {

    private static final boolean DEBUG = false;
    private static final Logger logger =
            LoggerManager.getLogger(GenerateTocDialog.class, DEBUG);

    private static GenerateTocDialog instance = null;

    private JLabel fileNameLabel = new JLabel(getLocText("gui.bookfiles.generate.file_name"));
    private JTextField fileNameField = new JTextField();

    private JLabel tocTitleLabel = new JLabel(getLocText("gui.bookfiles.generate.toc_title"));
    private JTextField tocTitleField = new JTextField();

    private JLabel levelsLabel = new JLabel(getLocText("gui.bookfiles.generate.toc_levels"));
    private JComboBox levelsCombo = new JComboBox(
            new String[] {"H1", "H2", "H3", "H4", "H5", "H6"});

    private JButton generateButton = new JButton(
            getLocText("gui.bookfiles.generate.generate"), Images.getImage(OK));
    private JButton cancelButton = new JButton(
            getLocText("gui.cancel"), Images.getImage(CANCEL));

    private JLabel anchorsLabel = new JLabel(getLocText("gui.bookfiles.generate.toc_note_anchors"));

    private TocGenerator tocGen;

    // -----

    /** */
    private GenerateTocDialog() {
        super(MainFrame.getInstance());
        initComponents();
        initLayout();
        initEventHandlers();
        initDialog();
    }

    /**
     *
     * @return
     */
    private static GenerateTocDialog getInstance() {
        if (instance == null) {
            instance = new GenerateTocDialog();
        }
        return instance;
    }


    
    
    /**
     *
     * @param bookFiles
     * @return
     */
    public static String showDialog(BookFiles bookFiles)  {
        getInstance();

        return instance.showThisDialog(bookFiles);
    }

    /**
     *
     * @param bookFiles
     */
    private String showThisDialog(BookFiles bookFiles) {
        generatedFileName = null;
        this.bookFiles = bookFiles;

        if (bookFiles != null) {
            tocGen = new TocGenerator(bookFiles);

            setVisible(true);
        }

        return generatedFileName;
    }

    /**
     *
     */
    private void initDialog() {
        setTitle(getLocText("gui.bookfiles.generate.toc.title"));

        pack();
        setMinimumSize(new Dimension(450, getHeight()+35));
        setSize(getMinimumSize());

        setLocationRelativeTo(MainFrame.getInstance());

        GuiUtils.addHideActionWithEscapeKey(this);
    }

    /**
     *
     */
    private void initComponents() {
        anchorsLabel.setPreferredSize(new Dimension(1, 1));

        fileNameLabel.setLabelFor(fileNameField);
        tocTitleLabel.setLabelFor(tocTitleField);
        levelsLabel.setLabelFor(levelsCombo);

        fileNameField.setEditable(false);

        fileNameField.setText(BookFiles.DEFAULT_TOC_FILENAME);
        tocTitleField.setText(getLocText("gui.bookfiles.generate.toc_title.default"));
        levelsCombo.setSelectedItem("H3");
        
        levelsCombo.setToolTipText(getLocText("gui.bookfiles.generate.toc_levels.tooltip"));
        
        getRootPane().setDefaultButton(generateButton);
    }

    /**
     *
     */
    private void initLayout() {
        this.setLayout(new MigLayout("",
                "unrel[label]rel[fill,grow]unrel",
                "unrel[]para[]rel[]rel[]para[grow,bottom,nogrid]unrel"));

        this.add(fileNameLabel);
        this.add(fileNameField, "wrap, sgy a");

        this.add(tocTitleLabel);
        this.add(tocTitleField, "wrap, sgy a");

        this.add(levelsLabel);
        this.add(levelsCombo, "wrap, sgy a");

        this.add(anchorsLabel, "skip, wrap");

        this.add(generateButton, "tag ok, sg b");
        this.add(cancelButton, "tag cancel, sg b");
    }

    /**
     *
     */
    private void initEventHandlers() {

        generateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                generate();

                if (generatedFileName != null) {
                    setVisible(false);
                }
            }
        });

        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
            }
        });

        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                setVisible(false);
            }
        });
    }

    /**
     *
     */
    @Override
    protected void generate() {
        if (tocGen == null) {
            throw new IllegalStateException("tocGen = null");
        }

        try {
            bookFiles.setDefaultToc();

//        if (bookFiles.getToc().exists()) {
//            int res = JOptionPane.showConfirmDialog(this,
//                    "Soubor existuje, přepsat?", "Dotaz", JOptionPane.YES_NO_OPTION);
//            if (res != JOptionPane.YES_OPTION) {
//                return;
//            }
//        }

            bookFiles.getToc().setTitleInToc(tocTitleField.getText());

            // H3 --> 3
            String levelText =
                    levelsCombo.getSelectedItem().toString().substring(1);
            try {
                int levelNum = Integer.parseInt(levelText);
                tocGen.setLevel(levelNum);
            } catch (NumberFormatException ex) {
                logger.warning("(" + levelText + ")  --  " + ex.toString());
            }

            tocGen.generate();

            generatedFileName = bookFiles.getToc().getPath();
            // ----

            generateBaseStyle();

        } catch (IOException ex) {
            logger.warning(ex.toString());
            if (DEBUG) {  ex.printStackTrace();  }
            Dialogs.showErrorDialog(ex);
        }

    }

}   // GenerateTocDialog.java

